var flag = [0, 0];

$(function() {
	getPath();
	init();
//	showData("");
	$("#normalSure").attr('disabled',true);
	var emailTest = /^([\.a-zA-Z0-9_-])+@([\.a-zA-Z0-9_-])+(\.[cn_-])+/;
	$("#email").blur(function() {
		var email = $(this).val();
		if(email == "" || email == null) {
			return ;
		}
		if(!emailTest.test(email)) {
			alertMsg("请输入正确的收件人邮箱");
			flag[0] = 0;
		} else {
			flag[0] = 1;
			if(flag[1] == 1) {
				$("#normalSure").attr('disabled',false);
			}
		}
	});
	$("#all-check").click(function() {
		
		$("input[name='iconCheck']").each(function() {
			$(this).attr('checked',true);
		});
		
		
	});
	$("#emailFrom").blur(function() {
		var email = $(this).val();
		if(email == "" || email == null) {
			return ;
		}
		if(!emailTest.test(email)) {
			alertMsg("请输入正确的联系邮箱");
		} else {
			flag[1] = 1;
			if(flag[0] == 1) {
				$("#normalSure").attr('disabled',false);
			}
		}
	});
});

var basePath = "";

function init() {
	var urlParam = getUrlParam();
	var jsonParam = {};
	jsonParam.quoId = urlParam.quoId;
	jsonParam.sign = urlParam.sign;
	padMarketing.ajaxNormal('/pad_marketing/main/quoInitShare.action',jsonParam,
		function(data){
			showData(data);
		},
		function(data){
			console.log('失败');
			alertMsg("网络异常,请重新加载!", 0, function() {
				window.location.reload();
			});
		}
	);
}

function getPath() {	
	padMarketing.ajaxNormal(
			'/pad_marketing/main/path.action',
			{'path':'domain'},
			function(result){
				basePath=result.result;	
			}
	);
}

var productName = "";
var emailParam = {};
var status = '';

function showData(data) {
	var urlParam = getUrlParam();
//	console.log(urlParam);
	var quoBase = data['quoBase'];
	productName = quoBase.productName;
	status = quoBase.status;
	emailParam.phName = data['quoBase'].phName;
	data = data['faceImgs'];
//	console.log(data);
	var tpl_scroller = document.getElementById("tpl_scroller").innerHTML;
	var scrollers = [];
	var scroller_list = [];
	var indicator_list = [];
	var a = 0;
	for(var i = 0; i < data.length; i++) {
//		console.log(data[0].val);
		var scroller_html = tpl_scroller.replace(/\{imgPath\}/g, data[i].val);
//		var scroller_html = tpl_scroller;
		scroller_list.push(scroller_html);
		if((parseInt(i) + 1) % 5 == 0 || (parseInt(i) + 1) == data.length) {
//			console.log((parseInt(i) + 1));
//			console.log(scroller_list);
			var scroller_list_ul = "<li><ul>" + scroller_list.join('') + "</ul></li>";
//			console.log(scroller_list_ul);
			scrollers.push(scroller_list_ul);
			scroller_list = [];
			if((parseInt(i) + 1) <= 5) {
				indicator_list.push("<li class='active'>" + parseInt(++a) + "</li>");
			} else {
				indicator_list.push("<li class=''>" + parseInt(++a) + "</li>");
			}
		}
	}
	scrollers = "<ul>" + scrollers.join('') + "</ul>";
	var widthValue = Math.ceil(data.length / 5) * 1024;
//	console.log(widthValue);
	$("#scroller").width(widthValue);
	$("#scroller").html(scrollers);
//	console.log(indicator_list);
	$(".indicator").html(indicator_list.join(''));
	myScroll3.refresh();
	$("input[name='cover'][value='" + quoBase.faceImg + "']").attr("checked", true);
	var proposalName = quoBase.quoName != "" ? quoBase.quoName : quoBase.phName;
	$("input[id='proposal-name']").val(proposalName);
	if(urlParam.benefit) {
		for(attr in urlParam) {
			if(urlParam[attr] == 'true') {
				$("input[name='iconCheck'][value='" + attr + "']").attr("checked", true);
			}
		}
	}
}

function checkInput(id) {
	var quoName = $("#proposal-name").val();
	var faceImg = $("input[name='cover']:checked").val();
	if(!quoName) {
		alertMsg("请输入建议书名称");
		return ;
	}
	if(!faceImg) {
		alertMsg("请选择一个封面");
		return ;
	}
	showDiv("open" + id);
}

function saveProposal(action) {
	var quoName = $("#proposal-name").val();
	var faceImg = $("input[name='cover']:checked").val();
	var json = sessionStorage.getItem("quoBase");
	json = eval( '(' + json + ')' );
	var jsonParam = {};
	jsonParam.quoId = json.quoId;
	jsonParam.sign = json.sign;
	jsonParam.quoName = quoName;
	jsonParam.faceImg = faceImg;
	if(status != 'F') {
		padMarketing.ajaxNormal('/pad_marketing/main/quoSaveQuoBase.action',jsonParam,
			function(data){
				console.log('success');
				status = 'F';
				toNextPage(action);
			},
			function(data){
				console.log('失败');
			}
		);
	} else {
		toNextPage(action);
	}
}

function toNextPage(action) {
	var iconCheck = ["frontCover", "company", "plan", "benefit", "clause", "illustration", "productSpec", "tips"];
	var icons = [];
	for(var i = 0; i < iconCheck.length; i++) {
		if(!icons[iconCheck[i]]) {
			icons[iconCheck[i]] = false;
		}
	}
	$("input[name='iconCheck']:checked").each(function() {
		icons[$(this).val()] = true;
	});
	var urlString = "";
	for(attr in icons) {
		urlString += "&" + attr + "=" + icons[attr];
	}
	var quoBase = sessionStorage.getItem("quoBase");
	quoBase = JSON.parse(quoBase);
	urlString = "?quoId=" + quoBase.quoId + "&sign=" + quoBase.sign + urlString;
//	console.log(urlString);
	if(action == 1) {
		window.location.href = "/pad_marketing/plan/shareWechat.action" + urlString + "&action=preview&imgPath=" + $("input[name='cover']:checked").val();
	} else if(action == 2) {
		window.location.href = "/pad_marketing/plan/proposalPreview.action" + urlString + "&action=preview";
	} else if(action == 3) {
		weixin(urlString, $("#proposal-name").val(), productName, basePath);
	} else if(action == 4) {
		emailParam.url =  basePath + "pad_marketing/plan/proposalPreview.action" + urlString + "&action=share";
		closeDiv('open2');
		getUserInfo();
	}
}

function getUrlParam() {
    var str = window.location.search;
    var objURL = {};
    str.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function ($0, $1, $2, $3) {
            objURL[$1] = $3;
        }
    );
    return objURL;
}

function checkMsg(target) {
	if(target.checked) {
		alertMsg("仅网页版使用");
	}
}

function getUserInfo() {
	padMarketing.ajaxNormal('/pad_marketing/main/getUser.action', "",
		function(data){
			var email = data.username.email;
			if(email != "" || email != null) {
				flag[1] = 1;
			}
			$("#emailFrom").val(email);
			showDiv('open3');
		},
		function(data){
			console.log('失败');
		}
	);
}

function sendEmail() {
	//收件人邮箱：receiver   
	//建议书名称：recommen    
	//客户姓名：name   
	//链接地址： actionUrl 
//	console.log(emailParam);
	var eamil = $("#email").val();
	if(!eamil) {
		alertMsg("请输入邮箱");
	}
	var receiver= $("#email").val(); 
	var recommen = $("#proposal-name").val();
	var name = emailParam.phName;
	var actionUrl = emailParam.url;
	var email = $("#emailFrom").val();
	if(!email){
		alertMsg("请输入邮箱地址");
		return
	}
	$("#normalSure").attr('disabled',true);
	$.post('/pad_marketing/main/sendMail.action',{"receiver":receiver,"recommen":recommen,"name":name,"actionUrl":actionUrl,"mail":email}).success(
		function (data) {
			$("#normalSure").attr('disabled',false);
			var truedata = data;
			if(truedata == 'true'){
				changeStatus();
			}else{
			    alertMsg("邮件发送失败,请重新发送");
			}
		}).error(function (data) {
		     $("#normalSure").attr('disabled',false);
		     alertMsg("邮件发送失败,请重新发送");
		}
	);
}

function changeStatus() {
	var json = sessionStorage.getItem("quoBase");
	json = JSON.parse(json);
	var jsonParam = {};
	jsonParam.quoId = json.quoId;
	jsonParam.sign = json.sign;
	padMarketing.ajaxNormal('/pad_marketing/main/quoAfterShare.action',jsonParam,
		function(data){
			alertMsg("邮件发送成功,请至邮箱查看");
	        closeDiv('open3');
		},
		function(data){
			console.log('失败');
		}
	)
}